package com.baoyouqun.service.impl;

import com.alibaba.cola.dto.Response;
import com.alibaba.cola.dto.SingleResponse;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baoyouqun.base.utils.ConvertUtils;
import com.baoyouqun.domain.CreateCmd.OrderRecordCreateCmd;
import com.baoyouqun.domain.Query.OrderRecordQuery;
import com.baoyouqun.domain.UpdateCmd.OrderRecordUpdateCmd;
import com.baoyouqun.domain.VO.OrderRecordVO;
import com.baoyouqun.entity.OrderRecord;
import com.baoyouqun.entity.UserVipTime;
import com.baoyouqun.mapper.OrderRecordMapper;
import com.baoyouqun.service.OrderRecordService;
import com.baoyouqun.service.UserVipTimeService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.util.StringUtil;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Objects;

@Slf4j
@Service
public class OrderRecordServiceImpl extends ServiceImpl<OrderRecordMapper, OrderRecord> implements OrderRecordService {

    @Resource
    private OrderRecordMapper orderRecordMapper;
    @Resource
    private UserVipTimeService userVipTimeService;

    @Override
    public SingleResponse<OrderRecordVO> create(OrderRecordCreateCmd cmd) {
        OrderRecord entity =
                ConvertUtils.copyBean(cmd, OrderRecord.class);
        Boolean result = save(entity);
        if (!result) {
            return SingleResponse.buildFailure("100101", "创建失败");
        }

        OrderRecordVO vo =
                ConvertUtils.copyBean(entity, OrderRecordVO.class);
        return SingleResponse.of(vo);
    }

    @Override
    public Response update(OrderRecordUpdateCmd cmd) {
        if (Objects.isNull(cmd)) {
            return Response.buildFailure("100301", "参数不能为空");
        }
        if (StringUtil.isBlank(cmd.getId())) {
            return Response.buildFailure("100302", "ID不能为空");
        }
        OrderRecord oldEntity = getById(cmd.getId());
        if (Objects.isNull(oldEntity)) {
            return Response.buildFailure("100303", "未查询到此数据");
        }
        oldEntity = ConvertUtils.copyBean(cmd, OrderRecord.class);
        Boolean result = updateById(oldEntity);
        if (result) {
            return Response.buildSuccess();
        } else {
            return Response.buildFailure("100304", "更新失败");
        }
    }

    @Override
    public OrderRecordVO selectById(String id) {
        OrderRecord entity = orderRecordMapper.selectById(id);
        OrderRecordVO vo =
                ConvertUtils.copyBean(entity, OrderRecordVO.class);
        return vo;
    }

    @Override
    public IPage<OrderRecordVO> pageVo(OrderRecordQuery query) {
        IPage<OrderRecord> page = new Page<OrderRecord>(query.getCurrent(), query.getSize());
        page = page(page, new LambdaQueryWrapper<OrderRecord>());
        Page<OrderRecordVO> voPage = new Page<>(page.getCurrent(), page.getSize(), page.getTotal());
        List<OrderRecordVO> records = ConvertUtils.copyBeanList(page.getRecords(), OrderRecordVO.class);
        voPage.setRecords(records);
        return voPage;
    }

    @Override
    public List<OrderRecordVO> selectByUserId(String userId) {
        List<OrderRecord> list = list(new LambdaQueryWrapper<OrderRecord>().eq(OrderRecord::getUserId, userId));
        return ConvertUtils.copyBeanList(list, OrderRecordVO.class);
    }

    @Override
    public boolean updateInvoiceStatus(String orderId, Byte status) {
        // 业务校验：例如检查订单是否存在
        OrderRecord order = getById(orderId);
        if (order == null) {
            return false;
        }

        // 执行更新
        OrderRecord updateOrder = new OrderRecord();
        updateOrder.setId(orderId);
        updateOrder.setStatus(status);
        updateOrder.setUpdateTime(LocalDateTime.now());
        boolean result = updateById(updateOrder);
        if (result && status != null && status == 1 && StringUtil.isNotBlank(order.getUserId())) {
            handleUserVipTime(order.getUserId());
        }

        return result;
    }

    /**
     * 处理用户会员有效期（新增或延长1年）
     */
    private void handleUserVipTime(String userId) {
        if (userId == null) {
            log.warn("用户ID为空，无法处理会员时间");
            return;
        }

        // 查询用户当前会员记录
        UserVipTime userVipTime = userVipTimeService.getOne(new LambdaQueryWrapper<UserVipTime>().eq(UserVipTime::getUserId, userId).last("limit 1"));


        LocalDateTime now = LocalDateTime.now();

        if (userVipTime == null) {
            // 新增会员记录：从当前时间开始，有效期1年
            userVipTime = new UserVipTime();
            userVipTime.setUserId(userId);
            userVipTime.setStartTime(now);
            userVipTime.setEndTime(now.plusYears(1));
            userVipTime.setCreateTime(now);
            userVipTime.setVipLevelId("001");
            userVipTimeService.save(userVipTime);
        } else {
            // 更新会员记录：在原有结束时间基础上延长1年
            LocalDateTime newEndTime = userVipTime.getEndTime().isAfter(now)
                    ? userVipTime.getEndTime().plusYears(1)  // 会员未过期，从原结束时间延长
                    : now.plusYears(1);                       // 会员已过期，从当前时间重新计算

            userVipTime.setEndTime(newEndTime);
            userVipTime.setVipLevelId("001");
            userVipTimeService.updateById(userVipTime);
        }
    }
}